package com.ifeng.stock;

import java.net.*;
import java.util.Arrays;
import java.io.*;

import com.tidemark.*;

public abstract class AbstractReader {


	/**
	 * 找出同时符合主力买入，散户卖出的股票，提示牛
	 * 找出同时符合主力卖出，散户买入的股票，提示熊
	 */
	protected void compare_print(ResultTable big, ResultTable small, String comment){
		
		Arrays.sort(big.table);
		Arrays.sort(small.table);
		
		for(int i=0,j=0; i<big.table.length && j<small.table.length; ){
			if(big.table[i].compareTo(small.table[j]) == 0 ){
				big.table[i].setComments(comment);
				model.addStock(big.table[i]);
				i++; j++;
				continue;
			}
			else if(big.table[i].compareTo(small.table[j]) < 0 ){
				i++;
				continue;
			}
			else{
				j++;
				continue;
			}
		}
		model.addSeparator();
	}
	
	protected ResultTable read(String queryUrl){
	    try 
	    {
	        URL url = new URL(queryUrl);
	    
	        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));
	        String str;
	        	ResultTable r = new ResultTable(Constants.maxstocks);
	        int i = 0;
			
	        while ((str = in.readLine()) != null) 
	        {
	        	//System.out.println(str);
	        	 String num = parser.parse(str);
	        	 if(num != null && i < r.table.length){
	        		 //got a stock number, save it
	        		 r.table[i].setCode(num);
	        		 
	        		 //read the stock name in the next line
	        		 str = in.readLine();
	        		 if(str == null){
	        			 System.out.println("Warning: failed to read stock name... " );
	        		 }
	        		 String temp = parser.parseName(str);
	        		 if(temp == null){
	        			 System.out.println("Warning: failed to read stock name... " );
	        		 }
	        		 r.table[i].setName (temp);

	        		 i++;
	        	 }
	        }

	        in.close();

	        if(i!=Constants.maxstocks){
		    	System.out.println("Warning: something wrong... " + i);
		    	return null;
		    }else{
		    	//System.out.println("parse page success!");
				return r;
		    }
	    } 
	    catch (MalformedURLException e) {e.printStackTrace(); return null;} 
	    catch (IOException e) {e.printStackTrace(); return null;}
	}
	
	protected Parser parser = new Parser();
	protected StockDataModel model;
	

	
}
